<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of OrderModel
 *
 * @author skyinter
 */
class orderGoodsModel extends Model {

	
	
    function __construct() {
        parent::__construct();
        $this->dbTable = 'order_goods';
        $this->page = 20;
    }

    /**
     * 获取订单商品信息
     */
    public function getOrderGoods($order_id, $field='*'){
    	$where  = '`order_id` = ' . $order_id;
    	$result = $this->field($field)->where($where)->findAll();
    	return $result;
    }

    /**
     * 获取列表数据
     * @param   $page int 分页数据，默认是第一页
     * @return  $result array 返回查询数组
     */
    public function get_list($page = 1, $where = ' 1=1 '){
        $result = $this->page($page, $this->page)->where($where)->order('`id` desc')->findAll();
        return $result;
    }
    
    /**
     * 添加订单商品
     * @param Int $order_id  订单id
     * @param Array $goods_arr 商品数组(key为商品id，value为数量)
     * @return Int 新增记录数量
     */
    public function add($order_id, $goods_arr){

        $goods_id_arr  = array();
        $goods_num_arr = array();
        $goods_ids     = '';

        foreach ($goods_arr as $k => $v) {
            $goods_id_arr[]  = $k;
            $goods_num_arr[] = $v;
            $goods_ids      .= $k.',';
        }
        $goods_ids = rtrim($goods_ids, ',');

        $goods_info = M('goods')
                    ->field('`id`,`goods_name`,`goods_price`,`goods_image`,`score`,`quota`')
                    ->where("`id` in ($goods_ids)")
                    ->findAll();

        // z($goods_info);
        $insert_arr = array();
        foreach ($goods_info as $k => $v) {
            $insert_arr[] = array(
                'order_id'    => $order_id,
                'goods_id'    => $v['id'],
                'goods_num'   => $goods_num_arr[$k],
                'goods_price' => $v['goods_price'],
                'goods_name'  => $v['goods_name'],
                'goods_image' => $v['goods_image'],
                'score'       => $v['score'],
                'is_restrict' => $v['quota']>0 ? 1 : 0,
            );
        }

        $result = M('order_goods')->insertAll($insert_arr);
        return $result;
    }

}